package com.service;

import com.dao.BackUserRepository;
import com.model.BackUser;
import com.model.FrontUser;
import com.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class BackUserService {
    @Autowired
    private BackUserRepository repository;

    public boolean checkExists(BackUser user) {
       return repository.existsByUsername(user.getUsername());
    }

    public BackUser getByUsername(String username) {
        return repository.getByUsername(username);
    }


    public boolean register(BackUser user) {
        user.setRegisterTime(LocalDateTime.now());
        user.setPassword(Md5Utils.decodeBackUser(user));
        return repository.save(user) != null;
    }

    // 对比md5密码
    public boolean checkPasswordByUser(String password, BackUser user) {
        String db_md5 = user.getPassword();
        user.setPassword(password);
        String req_md5 = Md5Utils.decodeBackUser(user);
        user.setPassword(db_md5);
        return db_md5.equals(req_md5);
    }

    public List<BackUser> findAll() {
        return repository.findAll();
    }

    public boolean updateLoginTime(BackUser user, LocalDateTime now) {
        return repository.updateLoginTimeById(user.getId(), now) > 0;
    }
}
